import { useState, useEffect, useRef, useCallback, memo } from 'react'
import { connect } from 'react-redux';
import { useNavigate } from 'react-router-dom'
import { CSSTransition } from 'react-transition-group'
import {
    Container,
    ShortcutWrapper,
    HotKey,
    EnterLoading,
    List,
} from './style'
import SearchBox from '../../components/search-box'
import Loading from '@/components/loading'
import Scroll from '@/components/Scroll'
import Lazyload, { forceCheck } from 'react-lazyload';
import { getName } from '@/api/utils'
import { addSearchHistory, removeSearchHistory, getSearchHistory } from '@/utils'
import {
    // changeEnterLoading,
    getHotwords,
    getSuggestList
} from './store/actionCreators'

const Search = (props) => {
    const {
        suggestList,
        hotList
    } = props
    const {
        getHotwordsDispatch,
        changeEnterLoadingDispatch,
        getSuggestListDispatch,
    } = props;
    const navigate = useNavigate();
    
    const [query, setQuery] = useState('');
    const [show, setShow] = useState(false);
    const [history, setHistory] = useState([])

    // console.log(history);

    // useEffect(() => {
        
    // },[history])

    useEffect(() => {
        setShow(true);
        // if (!hotList.size)
        getHotwordsDispatch();
        // eslint-disable-next-line
        const history = getSearchHistory();
        setHistory(history)
    }, []);

    useEffect(() => {
        // console.log(query)
        if (query.trim()) {
            // if 去掉空字符后还有值
            // changeEnterLoadingDispatch(true);
            getSuggestListDispatch(query);
        }
    }, [query])

    const searchBack = useCallback(() => {
        setShow(false)
    }, [])

    const handleQuery = (q) => {
        // console.log(q)
        // 给子组件防抖后得到的数据修改方法
        setQuery(q)
    }
    const linkTo = (value) => {
        addSearchHistory(value)
        navigate(`/search?keyword=${value}`)
        setTimeout(() => {
            navigate('/shouye')
        },1000)
    }
    const removeHistory = () => {
        removeSearchHistory()
        setHistory([])
    }
    const renderSuggests = () => {
        // let list = hotList ? hotList : [];
        return (
            <div className="m-search-suggest">
                <ul className="suggest-list">
                    {
                        suggestList.map(item => {
                            return (
                                <li key={item.value} onClick={() => linkTo(item.value)} dangerouslySetInnerHTML={{ __html: `${item.name}` }}></li>
                            )
                        })
                    }
                </ul>
            </div>
        )
    }
    const renderHotwords = () => {
        return (
            <div className="m-search-hot">
                <h2 className="title">大家都在搜</h2>
                <div className="list">
                    {
                        hotList.map(item => {
                            return (
                                <span key={item.hot_id} onClick={() => linkTo(item.keyword)} className="hotword-item">{item.keyword}</span>
                            )
                        })
                    }
                </div>
            </div>
        )
    }
    const renderHistory = () => {
        const list = history ? history : [];
        return (
            <div className="m-search-history">
                <h2 className="title">历史搜索</h2>
                <ul className="history-list">
                    {
                        list.map(item => {
                            return (
                                <li key={item.value}
                                    onClick={() => linkTo(item.value)}
                                >
                                    <i className="iconfont History"></i>
                                    <a>{item.value}</a>
                                </li>
                            )
                        })
                    }
                </ul>
                <div className="clear-history" onClick={() => removeHistory()}>
                    <a>清除历史记录</a>
                </div>
            </div>
        )
    }
    return (
        <>
            <CSSTransition
                in={show}
                timeout={300}
                appear={true}
                classNames="fly"
                unmountOnExit
                onExit={() => {
                    navigate(-1)
                }}
            >
                <Container>
                    <div className="search_box_wrapper">
                        <SearchBox
                            back={searchBack}
                            newQuery={query}
                            handleQuery={handleQuery}
                        >
                        </SearchBox>
                    </div>
                    <ShortcutWrapper show={!query}>
                        {/* props 传值给 styled-components 做样式业务 */}
                        {renderHotwords()}
                        {renderHistory()}
                        {/* <Scroll>
                            <div>
                                <HotKey>
                                    <h1 className='title'>热门搜索</h1>
                                    {renderHotKey()}
                                </HotKey>
                            </div>
                        </Scroll> */}
                    </ShortcutWrapper>
                    <ShortcutWrapper show={query}>
                        <Scroll onScroll={forceCheck}>
                            <div>
                                {renderSuggests()}
                            </div>
                        </Scroll>
                    </ShortcutWrapper>
                    {/* {enterLoading && <EnterLoading><Loading></Loading></EnterLoading>} */}
                </Container>
            </CSSTransition>
        </>
    )
}
const mapStateToProps = (state) => {
    return {
        // api 请求 在 redux 中
        // 跨模块共享数据
        hotList: state.search.hotList,
        // 自己模块的 enterLoading
        // enterLoading: state.search.enterLoading,
        // 搜索建议 广告
        suggestList: state.search.suggestList,
        // songsCount: state.player.playList.length,
        // songsList: state.search.songsList
    }
}
// container Part
const mapDispatchToProps = (dispatch) => {
    return {
        getHotwordsDispatch() {
            dispatch(getHotwords());
        },
        // changeEnterLoadingDispatch(data) {
        //     dispatch(changeEnterLoading(data))
        // },
        getSuggestListDispatch(data) {
            // console.log(data);
            dispatch(getSuggestList(data))
        },
        // getSongsListDispatch(data) {
        //     dispatch(getSongsList(data))
        // }
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(memo(Search))
